import {Injectable} from "@angular/core";
import {RequestServerHTTPService} from "../../../shared/service/request-server-HTTP.service";
import {Observable} from "rxjs/Observable";
import {ResultEntity} from "../../../shared/model/resultEntity";
import {CommodityBaseInfoModel} from "../../../shared/model/commodity-info.model";
import {CommodityTypeModel} from "../../../shared/model/commodity-type.model";
/**
 * 主页访问后台的http服务
 * Created by wubin on 2016-12-04.
 */
@Injectable()
export class IndexHttpService {
    private readonly selectIndexCarouselImgURL = "img/selectCarouselImgInfo.do";
    private readonly retrieveImgURL = "img/selectCarouselImg.do";
    private readonly retrieveCommodityInfoURL = "indexCommodity/baseInfo.do?commodityTypeId=%s";
    private readonly retrieveCommodityTypeURL = "indexCommodity/retrieveAllCommodityType.do";

    constructor(private requestServerHttpService: RequestServerHTTPService) {

    }

    /**
     * 该方法返回的是主页轮播图的id数组
     * @returns id数组
     */
    selectIndexCarouselImg(): Observable<String[]> {
        return new Observable<number[]>((observer) => {
            this.requestServerHttpService.getRequestServerForBack(this.selectIndexCarouselImgURL, null,
                (data: ResultEntity) => {
                    observer.next(data.result);
                },
                (error) => {
                    observer.error(error);
                });
        }).map((data): string[] => {
            let result: string[] = [];
            for (let i = 0; i < data.length; i++) {
                result[i] = this.retrieveImgURL + "?imageId=" + data[i];
            }
            return result;
        });
    }

    selectCommodityInfo(): Observable<CommodityBaseInfoModel> {
        return new Observable<any>((observer) => {

        });
    }

    /**
     * 该方法用于获得商品的类型信息
     * @returns {Observable<CommodityTypeModel[]>} 商品信息的模型对象
     */
    selectCommodityTypeInfo(): Observable<CommodityTypeModel[]> {
        return new Observable<any[]>((observer) => {
            this.requestServerHttpService.getRequestServerForBack(this.retrieveCommodityTypeURL, null,
                (data: ResultEntity) => {
                    observer.next(data.result);
                },
                (error) => {
                    observer.error(error);
                }
            )
        }).map((data): CommodityTypeModel[] => {
            let result: CommodityTypeModel[] = [];
            for (let i = 0, length = data.length; i < length; i++) {
                let oneData = data[i],
                    url: string = this.retrieveCommodityInfoURL.replace(/%s/, oneData.id);
                result[i] = new CommodityTypeModel(oneData.id, url, oneData.typeName);
            }
            return result;
        });
    }
}
